﻿using System;
using System.Reflection;
using System.ServiceModel.Activation;
using UFIDA.U9.WSS.ProxyService.Exceptions;
using UFIDA.U9.WSS.ProxyService.Interfaces;
using UFIDA.U9.WSS.ProxyService.Models;
using UFSoft.UBF.Service.Base;

namespace UFIDA.U9.WSS.ProxyService.Services
{
    /// <summary>
    ///     代理(Context)服务
    /// </summary>
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class ProxyService : IProxyService
    {
        /// <summary>
        ///     执行代理请求
        /// </summary>
        /// <param name="context"></param>
        /// <param name="proxy"></param>
        /// <returns></returns>
        public ReturnMessage<object> Do(ContextInfo context, ProxyBase proxy)
        {
            if (context == null)
                throw new WSException(ExceptionCodes.ServiceUserNotAuthenticated, "user not authenticated");
            if (proxy == null)
                throw new WSException(ExceptionCodes.ProxyServiceProxyPropertyIsIncorrect, "proxy is incorrect");
            //构建Session
            using (new SessionObject(context))
            {
                MethodInfo methodInfo = proxy.GetType().GetMethod("Do", new Type[] { });
                if (methodInfo == null)
                    throw new WSException(ExceptionCodes.ProxyServiceProxyPropertyIsIncorrect,
                        "no find Do() method in proxy");
                object result = methodInfo.Invoke(proxy, null);
                return new ReturnMessage<object>(result);
            }
        }
    }
}